package com.service.sso.sdk.service;

import com.alibaba.fastjson.JSONObject;
import com.service.sso.sdk.dto.UserDto;
import com.service.sso.sdk.event.UserLogoutEvent;
import com.service.sso.sdk.mapper.SsoUserMapper;
import com.service.sso.sdk.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class SsoUserService {
    @Autowired
    HttpServletRequest request;
    @Autowired
    SsoUserMapper ssoUserMapper;
    @Autowired
    ApplicationContext context;

    public UserModel getUser() {
        return JSONObject.parseObject(String.valueOf(request.getSession().getAttribute("user")), UserModel.class);
    }


    public void setUser(UserDto userDto) {
        request.getSession().setAttribute("user", JSONObject.toJSONString(ssoUserMapper.dtoToModel(userDto)));
    }

    public void logout() {
        UserModel userModel = getUser();
        if (null != userModel) {
            context.publishEvent(new UserLogoutEvent(this, userModel));
            request.getSession().invalidate();
        }
    }
}
